<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ disabled: disableSubmit }"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <!-- 采购单信息 -->
        <a-card :bordered="false" title="采购入库信息" style="margin-bottom: 16px">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="采购单号" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                <a-select
                  placeholder="请选择采购单号"
                  v-decorator="['purchaseOrderNo', validatorRules.purchaseOrderNo]"
                  @search="handlePurchaseOrderSearch"
                  @change="handlePurchaseOrderChange"
                  showSearch
                  optionFilterProp="children"
                >
                  <a-select-option v-for="order in purchaseOrders" :key="order.id" :value="order.id">
                    {{ order.purchaseNo }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="入库日期" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                <a-date-picker
                  style="width: 100%"
                  v-decorator="['inboundDate', validatorRules.inboundDate]"
                  placeholder="请选择入库日期"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="仓库" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                <j-select-warehouse
                  v-decorator="['warehouseId', validatorRules.warehouseId]"
                  placeholder="请选择仓库"
                  :trigger-change="true"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                <a-textarea
                  v-decorator="['remark']"
                  placeholder="请输入备注"
                  :rows="2"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        
        <!-- 采购单明细 -->
        <a-card :bordered="false" title="采购单物料明细" style="margin-bottom: 16px">
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="detailList"
            :pagination="false">
            
            <!-- 物料类型 -->
            <template slot="materialTypeSlot" slot-scope="text">
              <a-tag :color="
                text == '1' ? 'blue' : 
                text == '2' ? 'green' : 
                text == '3' ? 'orange' : 
                text == '4' ? 'purple' : 
                text == '5' ? 'red' : 
                text == '6' ? 'yellow' : ''"
              >
                {{ 
                  text == '1' ? '型材' : 
                  text == '2' ? '配件' : 
                  text == '3' ? '辅件' : 
                  text == '4' ? '其他' : 
                  text == '5' ? '余料' : 
                  text == '6' ? '半料' : '-'
                }}
              </a-tag>
            </template>
            
            <!-- 入库数量 -->
            <template slot="inboundQuantitySlot" slot-scope="text, record, index">
              <a-input-number
                v-model="record.inboundQuantity"
                :min="0"
                :max="record.quantity - (record.receivedQuantity || 0)"
                :precision="2"
                :step="1"
                style="width: 100%"
                @change="() => handleQuantityChange(index)"
              />
            </template>
            
            <!-- 推荐仓位 -->
            <template slot="locationSlot" slot-scope="text, record, index">
              <j-select-warehouse-location
                v-model="record.locationId"
                :warehouseId="form.getFieldValue('warehouseId')"
                @change="(value, option) => handleLocationChange(value, option, index)"
              />
            </template>
          </a-table>
        </a-card>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
import moment from 'moment'

export default {
  name: 'PurchaseInboundModal',
  components: {
    JSelectWarehouse,
    JSelectWarehouseLocation
  },
  data() {
    return {
      title: '采购入库',
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      model: {},
      form: this.$form.createForm(this),
      validatorRules: {
        purchaseOrderNo: {
          rules: [{ required: true, message: '请选择采购单号!' }]
        },
        inboundDate: {
          rules: [{ required: true, message: '请选择入库日期!' }]
        },
        warehouseId: {
          rules: [{ required: true, message: '请选择仓库!' }]
        }
      },
      purchaseOrders: [],
      detailList: [],
      purchaseOrderId: '', // 选中的采购单ID
      columns: [
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode',
          width: 120
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName',
          width: 150
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' }
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specification',
          width: 120
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
          width: 80
        },
        {
          title: '采购数量',
          align: 'center',
          dataIndex: 'quantity',
          width: 100
        },
        {
          title: '已入库数量',
          align: 'center',
          dataIndex: 'receivedQuantity',
          width: 100
        },
        {
          title: '本次入库数量',
          align: 'center',
          dataIndex: 'inboundQuantity',
          width: 120,
          scopedSlots: { customRender: 'inboundQuantitySlot' }
        },
        {
          title: '推荐仓位',
          align: 'center',
          dataIndex: 'locationId',
          width: 150,
          scopedSlots: { customRender: 'locationSlot' }
        }
      ],
      url: {
        purchaseOrders: '/wms/purchase/getApprovedUncompletedList',
        purchaseDetail: '/wms/purchase/queryDetailByOrderNo',
        createInbound: '/wms/inbound/add'
      }
    }
  },
  methods: {
    show(id) {
      this.visible = true
      this.purchaseOrderId = ''
      this.detailList = []
      
      this.$nextTick(() => {
        this.form.resetFields()
        // 设置今天为默认入库日期
        this.form.setFieldsValue({
          inboundDate: moment()
        })
        
        // 加载未完成的采购单
        this.loadPurchaseOrders()
        
        if (id) {
          this.purchaseOrderId = id
          this.form.setFieldsValue({
            purchaseOrderNo: id
          })
          this.loadPurchaseDetail(id)
        }
      })
    },
    loadPurchaseOrders() {
      getAction(this.url.purchaseOrders).then(res => {
        if (res.success) {
          this.purchaseOrders = res.result || []
        } else {
          this.$message.error(res.message || '获取采购单列表失败')
        }
      })
    },
    handlePurchaseOrderSearch(value) {
      if (!value) {
        this.loadPurchaseOrders()
      } else {
        // 过滤已加载的采购单
        this.purchaseOrders = this.purchaseOrders.filter(order => 
          order.purchaseNo.toLowerCase().indexOf(value.toLowerCase()) >= 0
        )
      }
    },
    handlePurchaseOrderChange(value) {
      this.purchaseOrderId = value
      this.loadPurchaseDetail(value)
    },
    loadPurchaseDetail(purchaseOrderId) {
      this.confirmLoading = true
      getAction(this.url.purchaseDetail, { purchaseOrderId }).then(res => {
        if (res.success && res.result) {
          const { details } = res.result
          
          // 设置明细数据，添加入库数量字段
          this.detailList = (details || []).map(detail => ({
            ...detail,
            inboundQuantity: detail.quantity - (detail.receivedQuantity || 0), // 默认入库剩余全部数量
            locationId: null // 推荐仓位，由后端推荐
          }))
          
          // 如果选择了仓库，自动推荐仓位
          const warehouseId = this.form.getFieldValue('warehouseId')
          if (warehouseId && this.detailList.length > 0) {
            this.recommendLocations(warehouseId)
          }
        } else {
          this.$message.error(res.message || '获取采购单详情失败')
        }
        this.confirmLoading = false
      }).catch(() => {
        this.confirmLoading = false
      })
    },
    recommendLocations(warehouseId) {
      // 收集物料类型
      const materialTypes = [...new Set(this.detailList.map(item => item.materialType))]
      
      // 调用推荐接口
      getAction('/wms/location/recommendLocationsByMaterialTypes', { 
        warehouseId, 
        materialTypes: materialTypes.join(',')
      }).then(res => {
        if (res.success && res.result) {
          // 获取推荐结果
          const recommendations = res.result
          
          // 更新明细中的推荐仓位
          this.detailList = this.detailList.map(item => {
            const rec = recommendations.find(r => r.materialType === item.materialType)
            if (rec) {
              return {
                ...item,
                locationId: rec.locationId
              }
            }
            return item
          })
        }
      })
    },
    handleQuantityChange(index) {
      const detail = this.detailList[index]
      // 确保入库数量不超过可入库数量
      const maxQuantity = detail.quantity - (detail.receivedQuantity || 0)
      if (detail.inboundQuantity > maxQuantity) {
        this.$set(this.detailList[index], 'inboundQuantity', maxQuantity)
      }
      if (detail.inboundQuantity < 0) {
        this.$set(this.detailList[index], 'inboundQuantity', 0)
      }
    },
    handleLocationChange(value, option, index) {
      this.$set(this.detailList[index], 'locationId', value)
      this.$set(this.detailList[index], 'locationName', option ? option.label : '')
    },
    handleOk() {
      // 表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          // 明细验证
          if (!this.detailList.length) {
            this.$message.warning('没有采购单明细数据')
            return
          }
          
          // 检查是否有物料选择了入库数量
          const hasInboundItems = this.detailList.some(item => item.inboundQuantity > 0)
          if (!hasInboundItems) {
            this.$message.warning('请至少输入一个物料的入库数量')
            return
          }
          
          // 检查推荐仓位
          const missingLocation = this.detailList.find(item => 
            item.inboundQuantity > 0 && !item.locationId
          )
          if (missingLocation) {
            this.$message.warning(`物料 ${missingLocation.materialName} 未选择入库仓位`)
            return
          }
          
          // 组装提交数据
          const formData = {
            ...values,
            inboundDate: values.inboundDate ? values.inboundDate.format('YYYY-MM-DD') : null,
            purchaseOrderId: this.purchaseOrderId,
            businessType: '11', // 11表示采购入库
            details: this.detailList
              .filter(item => item.inboundQuantity > 0) // 只提交入库数量大于0的记录
              .map(item => ({
                materialCode: item.materialCode,
                materialName: item.materialName,
                materialType: item.materialType,
                specification: item.specification,
                unit: item.unit,
                quantity: item.inboundQuantity,
                locationId: item.locationId,
                purchaseDetailId: item.id
              }))
          }
          
          this.confirmLoading = true
          
          // 提交入库单
          postAction(this.url.createInbound, formData).then(res => {
            if (res.success) {
              this.$message.success(res.message || '采购入库成功')
              this.handleCancel()
              this.$emit('ok')
            } else {
              this.$message.error(res.message || '采购入库失败')
            }
            this.confirmLoading = false
          }).catch(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.visible = false
      this.disableSubmit = false
      this.model = {}
      this.purchaseOrderId = ''
      this.detailList = []
    }
  }
}
</script>

<style scoped>
</style> 